<!--
 * IC卡信息管理
 *
-->
<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
                ><i
                    class="iconfont icon-ic-card"
                    style="margin: 5px; font-size: 22px"
                >
                    IC卡信息管理</i
                ></el-breadcrumb-item
            >
        </el-breadcrumb>

        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-input
                        placeholder="请输入用户名"
                        v-model="queryInfo.username"
                        clearable
                    ></el-input>
                </el-col>
                <el-col :span="4">
                    <el-input
                        placeholder="请输入IC卡号"
                        v-model="queryInfo.cardNo"
                        clearable
                    ></el-input>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="queryInfo.cardStatus" placeholder="请选择卡片状态" clearable>
                        <el-option label="正常" value="正常"></el-option>
                        <el-option label="挂失" value="挂失"></el-option>
                        <el-option label="注销" value="注销"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="success"
                        icon="iconfont icon-search-menu"
                        style="font-size: 18px"
                        @click="searchCards"
                    >
                        搜索</el-button
                    >
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="info"
                        icon="el-icon-refresh"
                        style="font-size: 18px"
                        @click="resetSearch"
                    >
                        重置</el-button
                    >
                </el-col>
                <el-col :span="2">
                    <el-button
                        size="small"
                        type="primary"
                        icon="iconfont icon-add-button"
                        style="font-size: 18px"
                        @click="openCard"
                    >
                        开卡</el-button
                    >
                </el-col>
                <el-col :span="4">
                    <el-button
                        size="small"
                        type="warning"
                        icon="iconfont icon-stall-fee-menu"
                        style="font-size: 18px"
                        @click="rechargeShow = true"
                    >
                        充值</el-button
                    >
                </el-col>
            </el-row>

            <!-- IC卡信息区域 -->
            <el-table v-loading="loading" :data="cards" border stripe>
                <el-table-column
                    width="50"
                    label="序号"
                    align="center"
                    type="index"
                ></el-table-column>
                <el-table-column label="IC卡号" prop="cardNo" align="center">
                    <template slot-scope="scope">
                        <div class="card-no">
                            <i class="icon-ic-card mini-card-icon"></i>
                            <span>{{ scope.row.cardNo }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="用户名" prop="user.username" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.userLoading">
                            <i class="el-icon-loading"></i> 加载中...
                        </span>
                        <span v-else-if="scope.row.user">
                            {{ scope.row.user.username }}
                        </span>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" prop="user.nike" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.userLoading">
                            <i class="el-icon-loading"></i> 加载中...
                        </span>
                        <span v-else-if="scope.row.user">
                            {{ scope.row.user.nike }}
                        </span>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="IC卡类型" prop="icType" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.icType === '普通卡'" type="info">普通卡</el-tag>
                        <el-tag v-else-if="scope.row.icType === '月卡'" type="success">月卡</el-tag>
                        <el-tag v-else-if="scope.row.icType === '年卡'" type="warning">年卡</el-tag>
                        <el-tag v-else-if="scope.row.icType === 'VIP卡'" type="danger">VIP卡</el-tag>
                        <el-tag v-else>未知</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="卡片状态" prop="cardStatus" align="center">
                    <template slot-scope="scope">
                        <div class="card-status">
                            <el-tag type="success" v-if="scope.row.cardStatus === '正常'">
                                <i class="el-icon-check"></i> 正常
                            </el-tag>
                            <el-tag type="danger" v-else-if="scope.row.cardStatus === '挂失'">
                                <i class="el-icon-warning"></i> 挂失
                            </el-tag>
                            <el-tag type="info" v-else-if="scope.row.cardStatus === '注销'">
                                <i class="el-icon-close"></i> 注销
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="余额" prop="balance" align="center">
                    <template slot-scope="scope">
                        <span class="card-balance">{{ scope.row.balance }}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="办理日期" prop="createTime" align="center">
                    <template slot-scope="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="300">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.cardStatus === '正常'"
                            @click="handleCardLoss(scope.row)"
                            type="warning"
                            size="mini"
                        >挂失</el-button>
                        <el-button
                            v-if="scope.row.cardStatus === '挂失'"
                            @click="handleCardUnLoss(scope.row)"
                            type="success"
                            size="mini"
                        >解挂</el-button>
                        <el-button
                            v-if="scope.row.cardStatus !== '注销'"
                            @click="handleCardCancel(scope.row)"
                            type="danger"
                            size="mini"
                        >注销</el-button>
                        <el-button
                            @click="handleCardRecharge(scope.row)"
                            type="primary"
                            size="mini"
                        ><i class="el-icon-wallet"></i> 充值</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <!-- 开卡对话框 -->
        <el-dialog
            title="IC卡开卡"
            :visible.sync="openCardShow"
            width="500px"
            center
            @close="openCardClose"
        >
            <div class="dialog-header">
                <i class="icon-ic-card dialog-icon"></i>
                <h4>新IC卡开通</h4>
            </div>
            <el-form
                :model="cardForm"
                :rules="cardRules"
                ref="cardRules"
                label-width="100px"
            >
                <el-form-item label="用户名" prop="username" class="is-required">
                    <el-select
                        v-model="cardForm.username"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入用户名"
                        :remote-method="remoteSearchUser"
                        :loading="userLoading"
                        style="width: 300px"
                    >
                        <el-option
                            v-for="item in userOptions"
                            :key="item.username"
                            :label="item.username + ' - ' + item.nike"
                            :value="item.username"
                        >
                            <span>{{ item.username }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.nike }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="IC卡号" prop="cardNo" class="is-required">
                    <el-input
                        v-model="cardForm.cardNo"
                        placeholder="请输入IC卡号"
                        style="width: 300px"
                    ></el-input>
                </el-form-item>
                <el-form-item label="IC卡类型" prop="icType" class="is-required">
                    <el-select v-model="cardForm.icType" placeholder="请选择IC卡类型" style="width: 300px">
                        <el-option label="普通卡" :value="0"></el-option>
                        <el-option label="VIP卡" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="初始余额" prop="balance" class="is-required">
                    <el-input
                        v-model.number="cardForm.balance"
                        placeholder="请输入初始余额"
                        style="width: 300px"
                    ></el-input>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="openCardClose()">取 消</el-button>
                <el-button type="primary" @click="submitCardForm('cardRules')"
                    >确认开卡</el-button
                >
            </span>
        </el-dialog>

        <!-- 充值对话框 -->
        <el-dialog
            title="IC卡充值"
            :visible.sync="rechargeShow"
            width="50%"
            center
            @close="rechargeShow = false"
        >
            <div class="dialog-header">
                <i class="icon-ic-card dialog-icon"></i>
                <h4>IC卡余额充值</h4>
            </div>
            <el-form
                :model="rechargeForm"
                :rules="rechargeRules"
                ref="rechargeRules"
                label-width="80px"
            >
                <el-form-item label="IC卡号" prop="cardNo">
                    <el-input v-model="rechargeForm.cardNo"></el-input>
                </el-form-item>
                <el-form-item label="金额" prop="amount">
                    <el-input v-model.number="rechargeForm.amount"></el-input>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="rechargeShow = false">取 消</el-button>
                <el-button type="primary" @click="rechargeConfirm('rechargeRules')"
                    >确认充值</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import axios from "axios";

export default {
    data() {
        var checkCardNo = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("IC卡号不能为空"));
            }
            
            // 调用API检查卡号是否存在
            axios.get(`http://localhost:9271/api/card/checkCardNo?cardNo=${value}`).then(response => {
                if (response.data.exists) {
                    callback(new Error("IC卡号已存在"));
                } else {
                    callback();
                }
            }).catch(() => {
                callback(new Error("卡号验证失败，请重试"));
            });
        };
        return {
            total: 0,
            loading: true,
            userLoading: false,
            queryInfo: {
                username: "",
                cardNo: "",
                cardStatus: "",
                pagenum: 1,
                pageSize: 6,
            },
            cards: [],
            userOptions: [],
            openCardShow: false,
            rechargeShow: false,
            cardForm: {
                username: "",
                cardNo: "",
                icType: 0,
                balance: 0
            },
            rechargeForm: {
                cardNo: "",
                amount: ""
            },
            cardRules: {
                username: [
                    { required: true, message: "请选择用户", trigger: "change" }
                ],
                cardNo: [
                    { validator: checkCardNo, trigger: "blur" }
                ],
                icType: [
                    { required: true, message: "请选择IC卡类型", trigger: "change" }
                ],
                balance: [
                    { required: true, message: "请输入初始余额", trigger: "blur" },
                    { type: 'number', message: "余额必须为数字", trigger: "blur" },
                    { type: 'number', min: 0, message: "余额不能小于0", trigger: "blur" }
                ]
            },
            rechargeRules: {
                cardNo: [
                    { required: true, message: "请输入IC卡号", trigger: "blur" }
                ],
                amount: [
                    { required: true, message: "请输入充值金额", trigger: "blur" },
                    { type: 'number', message: "充值金额必须为数字", trigger: "blur" },
                    { type: 'number', min: 1, message: "充值金额必须大于0", trigger: "blur" }
                ]
            }
        };
    },
    methods: {
        // 获取IC卡列表
        getList() {
            this.loading = true;
            // 构建查询参数字符串，与其他组件保持一致的请求风格
            let status = this.queryInfo.cardStatus === '正常' ? 1 : 
                         this.queryInfo.cardStatus === '挂失' ? 2 : 
                         this.queryInfo.cardStatus === '注销' ? 3 : '';
            
            // 直接使用后端服务器的完整URL
            let url = `http://localhost:9271/api/card/list?pagenum=${this.queryInfo.pagenum}&pageSize=${this.queryInfo.pageSize}`;
            
            // 添加其他查询参数
            if (this.queryInfo.cardNo) {
                url += `&cardNo=${this.queryInfo.cardNo}`;
            }
            
            if (status !== '') {
                url += `&status=${status}`;
            }
            
            // 如果有用户名，添加到控制台日志（实际项目中应该有一个API转换用户名为userId）
            if (this.queryInfo.username) {
                console.log("用户名查询暂未实现:", this.queryInfo.username);
                // 将来如果实现了，可以添加：url += `&username=${this.queryInfo.username}`;
            }
            
            console.log("请求URL:", url);
            
            axios.get(url).then(res => {
                this.loading = false;
                if (res.data.flag) {
                    console.log("获取卡片列表成功:", res.data);
                    
                    // 确保records存在，如果不存在则使用空数组
                    this.cards = res.data.data?.records || [];
                    this.total = res.data.data?.total || 0;
                    
                    // 检查每张卡的ID是否存在
                    this.cards.forEach((card, index) => {
                        if (!card.id) {
                            console.warn(`第${index+1}张卡片缺少ID字段`, card);
                        }
                    });
                    
                    // 获取每张卡对应的用户信息
                    this.fetchUserInfo();
                } else {
                    console.error("获取卡片列表失败:", res.data);
                    this.$message.error(res.data.message || '获取IC卡列表失败');
                }
            }).catch(error => {
                this.loading = false;
                console.error('获取IC卡列表失败', error);
                this.$message.error('获取IC卡列表失败，请检查网络连接或后端服务是否启动');
            });
        },
        
        // 获取用户信息
        async fetchUserInfo() {
            // 遍历卡列表，获取用户信息
            const promises = this.cards.map(async (card) => {
                if (card.userId) {
                    // 设置用户信息加载状态
                    this.$set(card, 'userLoading', true);
                    
                    try {
                        const { data: res } = await axios.get(`http://localhost:9271/user/getUserByUid?uid=${card.userId}`);
                        if (res.flag && res.data) {
                            // 将用户信息赋值给card.user
                            this.$set(card, 'user', res.data);
                        }
                    } catch (error) {
                        console.error(`获取用户ID=${card.userId}的信息失败`, error);
                    } finally {
                        // 取消加载状态
                        this.$set(card, 'userLoading', false);
                    }
                }
            });
            
            // 等待所有请求完成
            await Promise.all(promises);
        },
        
        // 分页变化
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            // 当每页显示数量变化时，将当前页重置为第一页
            this.queryInfo.pagenum = 1;
            this.getList();
        },
        
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getList();
        },
        
        // 远程搜索用户
        async remoteSearchUser(query) {
            if (query === '') {
                this.userOptions = [];
                return;
            }
            
            this.userLoading = true;
            try {
                const { data: res } = await axios.get(`http://localhost:9271/api/card/searchUsers?query=${query}`);
                if (res.code === "200" && res.flag) {
                    this.userOptions = res.data;
                } else {
                    this.$message.error('获取用户数据失败');
                    this.userOptions = [];
                }
            } catch (error) {
                console.error('搜索用户失败', error);
                this.$message.error('搜索用户失败，请检查网络连接');
                this.userOptions = [];
            } finally {
                this.userLoading = false;
            }
        },
        
        // 开卡
        openCard() {
            this.cardForm = {
                username: "",
                cardNo: "",
                icType: 0,
                balance: 0
            };
            this.openCardShow = true;
        },
        
        openCardClose() {
            this.openCardShow = false;
            this.$nextTick(() => {
                this.$refs.cardRules.resetFields();
            });
        },
        
        // 提交开卡表单
        async submitCardForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.loading = true;
                    try {
                        // 确保数据类型正确
                        const payload = {
                            username: this.cardForm.username,
                            cardNo: this.cardForm.cardNo,
                            icType: Number(this.cardForm.icType), // 确保是数字
                            balance: Number(this.cardForm.balance) // 确保是数字
                        };
                        
                        const { data: res } = await axios.post('http://localhost:9271/api/card/openCard', payload);
                        if (res.flag) {
                            this.$message.success("IC卡开卡成功！");
                            this.openCardShow = false;
                            this.getList();
                        } else {
                            this.$message.error(res.message || "IC卡开卡失败");
                        }
                    } catch (error) {
                        console.error('开卡失败', error);
                        this.$message.error('开卡失败，请检查网络连接');
                    } finally {
                        this.loading = false;
                    }
                } else {
                    return false;
                }
            });
        },
        
        // 格式化日期时间
        formatDateTime(dateTime) {
            if (!dateTime) return '';
            
            // 如果已经是格式化的字符串，直接返回
            if (typeof dateTime === 'string' && dateTime.includes('-')) {
                return dateTime;
            }
            
            const date = new Date(dateTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        
        // API 方法 - IC卡挂失
        async cardLossAPI(cardId) {
            try {
                console.log('开始调用挂失API, cardId:', cardId);
                const response = await axios.post('http://localhost:9271/api/card/cardLoss', { 
                    cardId: Number(cardId) // 确保是数字类型
                });
                console.log('挂失API响应:', response);
                
                return response.data && response.data.flag;
            } catch (error) {
                console.error('挂失API调用失败', error);
                this.$message.error('挂失操作失败: ' + (error.response?.data?.message || error.message || '未知错误'));
                return false;
            }
        },
        
        // API 方法 - IC卡解挂
        async cardUnLossAPI(cardId) {
            try {
                console.log('开始调用解挂API, cardId:', cardId);
                const response = await axios.post('http://localhost:9271/api/card/cardUnLoss', { 
                    cardId: Number(cardId) // 确保是数字类型
                });
                console.log('解挂API响应:', response);
                
                return response.data && response.data.flag;
            } catch (error) {
                console.error('解挂API调用失败', error);
                this.$message.error('解挂操作失败: ' + (error.response?.data?.message || error.message || '未知错误'));
                return false;
            }
        },
        
        // API 方法 - IC卡注销
        async cardCancelAPI(cardId) {
            try {
                console.log('开始调用注销API, cardId:', cardId);
                const response = await axios.post('http://localhost:9271/api/card/cardCancel', { 
                    cardId: Number(cardId) // 确保是数字类型
                });
                console.log('注销API响应:', response);
                
                return response.data && response.data.flag;
            } catch (error) {
                console.error('注销API调用失败', error);
                this.$message.error('注销操作失败: ' + (error.response?.data?.message || error.message || '未知错误'));
                return false;
            }
        },
        
        // API 方法 - IC卡充值
        async rechargeAPI(cardNo, amount) {
            try {
                console.log('开始调用充值API, cardNo:', cardNo, 'amount:', amount);
                const response = await axios.post('http://localhost:9271/api/card/recharge', { 
                    cardNo, 
                    amount: Number(amount) // 确保是数字类型
                });
                console.log('充值API响应:', response);
                
                return response.data && response.data.flag;
            } catch (error) {
                console.error('充值API调用失败', error);
                this.$message.error('充值操作失败: ' + (error.response?.data?.message || error.message || '未知错误'));
                return false;
            }
        },
        
        // 挂失
        async handleCardLoss(card) {
            // 检查卡片ID是否存在
            if (!card.id) {
                console.error('卡片数据缺少ID', card);
                this.$message.error('操作失败：卡片数据不完整');
                return;
            }
            
            const res = await this.$confirm(
                `确定要挂失卡号为 ${card.cardNo} 的IC卡吗?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            ).catch(err => err);
            
            if (res !== 'confirm') {
                this.$message.info("已取消操作");
                return;
            }
            
            this.loading = true;
            // 调用挂失API
            const success = await this.cardLossAPI(card.id); // 使用card.id替代card.cardId
            if (success) {
                this.$message.success("IC卡挂失成功！");
                this.getList(); // 重新获取列表刷新数据
            }
            this.loading = false;
        },
        
        // 解挂
        async handleCardUnLoss(card) {
            // 检查卡片ID是否存在
            if (!card.id) {
                console.error('卡片数据缺少ID', card);
                this.$message.error('操作失败：卡片数据不完整');
                return;
            }
            
            const res = await this.$confirm(
                `确定要解除卡号为 ${card.cardNo} 的IC卡挂失状态吗?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            ).catch(err => err);
            
            if (res !== 'confirm') {
                this.$message.info("已取消操作");
                return;
            }
            
            this.loading = true;
            // 调用解挂API
            const success = await this.cardUnLossAPI(card.id); // 使用card.id替代card.cardId
            if (success) {
                this.$message.success("IC卡解挂成功！");
                this.getList(); // 重新获取列表刷新数据
            }
            this.loading = false;
        },
        
        // 注销
        async handleCardCancel(card) {
            // 检查卡片ID是否存在
            if (!card.id) {
                console.error('卡片数据缺少ID', card);
                this.$message.error('操作失败：卡片数据不完整');
                return;
            }
            
            const res = await this.$confirm(
                `确定要注销卡号为 ${card.cardNo} 的IC卡吗? 注销后不可恢复！`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            ).catch(err => err);
            
            if (res !== 'confirm') {
                this.$message.info("已取消操作");
                return;
            }
            
            this.loading = true;
            // 调用注销API
            const success = await this.cardCancelAPI(card.id); // 使用card.id替代card.cardId
            if (success) {
                this.$message.success("IC卡注销成功！");
                this.getList(); // 重新获取列表刷新数据
            }
            this.loading = false;
        },
        
        // 单卡充值
        handleCardRecharge(card) {
            this.rechargeForm = {
                cardNo: card.cardNo,
                amount: ""
            };
            this.rechargeShow = true;
        },
        
        // 充值确认
        rechargeConfirm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.loading = true;
                    // 调用充值API
                    const success = await this.rechargeAPI(
                        this.rechargeForm.cardNo, 
                        this.rechargeForm.amount
                    );
                    
                    if (success) {
                        this.$message.success("充值成功！");
                        this.rechargeShow = false;
                        this.getList(); // 重新获取列表刷新数据
                    }
                    this.loading = false;
                } else {
                    return false;
                }
            });
        },
        searchCards() {
            this.queryInfo.pagenum = 1;
            this.getList();
        },
        resetSearch() {
            this.queryInfo.username = '';
            this.queryInfo.cardNo = '';
            this.queryInfo.cardStatus = '';
            this.queryInfo.pagenum = 1;
            this.getList();
        }
    },
    mounted() {
        this.getList();
    },
};
</script>

<style scoped>
.el-card {
    margin-top: 15px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-input, .el-select {
    margin-bottom: 15px;
}
.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 15px;
}
.card-icon {
    margin-right: 10px;
    font-size: 32px;
    color: #2b5d88;
}
.card-header h3 {
    margin: 0;
    color: #2b5d88;
}
.dialog-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 10px;
}
.dialog-icon {
    margin-right: 10px;
    font-size: 24px;
    color: #2b5d88;
}
.dialog-header h4 {
    margin: 0;
    color: #2b5d88;
}
.card-no {
    display: flex;
    align-items: center;
    justify-content: center;
}
.mini-card-icon {
    margin-right: 5px;
    font-size: 16px;
    color: #2b5d88;
}
.card-status {
    display: flex;
    justify-content: center;
}
.card-balance {
    font-weight: bold;
    color: #E6A23C;
}
.el-button+.el-button {
    margin-left: 5px;
}
.el-table .cell {
    padding: 8px 0;
}
</style> 